package mail

import (
	"context"
	"gitee.com/zylvcxq/gotham-utils/env"
	redis2 "gitee.com/zylvcxq/gotham-utils/redis"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-redis/redis/v8"
	"gopkg.in/gomail.v2"
)

/*
   @author:zhongyang
   @date:2023/8/20
   @description:邮件发送
*/

type EMailSender interface {
	SendMail(ctx context.Context, subject, body string) error
}

type RealMailSender struct {
	RedisClient *redis.Client
}

func NewRealMailSender(redisClient *redis.Client) *RealMailSender {
	return &RealMailSender{RedisClient: redisClient}
}

func (r *RealMailSender) SendMail(ctx context.Context, subject, body string) error {
	if r.RedisClient == nil {
		return nil
	}
	canSend := redis2.LimitByLuaScript(ctx, r.RedisClient)
	authorizeCode := env.GetEmailAuthorizeCode()
	// 进行邮件通知
	if canSend && authorizeCode != "" {
		m := gomail.NewMessage()
		//发送人
		m.SetHeader("From", "2635464756@qq.com")
		//接收人
		m.SetHeader("To", "2635464756@qq.com")
		//抄送人
		//m.SetAddressHeader("Cc", "xxx@qq.com", "xiaozhujiao")
		//主题
		m.SetHeader("Subject", subject)
		//内容
		m.SetBody("text/html", body)
		//附件
		//m.Attach("./myIpPic.png")

		//拿到token，并进行连接,第4个参数是填授权码
		d := gomail.NewDialer("smtp.qq.com", 587, "2635464756@qq.com", authorizeCode)

		// 发送邮件
		go func() {
			defer func() {
				if err := recover(); err != nil {
					log.Warnf("panic 发送失败 err:%v", err)
				}
			}()
			err := d.DialAndSend(m)
			if err != nil {
				log.Warnf("发送失败 err:%v", err)
				return
			}
		}()
	}
	return nil
}
